package org.vy.dal;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;



public class DBConnection
{

	protected Connection conn;

	protected ArrayList<Statement> arrStmt;


	protected DBConnection(Connection conn)
	{
		this.conn = conn;
		arrStmt = new ArrayList<Statement>();
	}


	public final void setAutoCommit(boolean bValue)
	{
		try{
			conn.setAutoCommit(bValue);
		}
		catch(SQLException ex)
		{
			throw new RuntimeException(ex);
		}
	}


	public final boolean getAutoCommit()
	{
		try{
			return conn.getAutoCommit();
		}
		catch(SQLException ex)
		{
			throw new RuntimeException(ex);
		}
	}


	public final void commit()
	{
		try{
			conn.commit();
		}
		catch(SQLException ex)
		{
			throw new RuntimeException(ex);
		}

	}

	public final void rollback()
	{
		try{
			conn.rollback();
		}
		catch(SQLException ex)
		{
			throw new RuntimeException(ex);
		}

	}

	public final void closeStatements() throws SQLException
	{
		if(conn != null && !conn.isClosed())
		{
			for(int i=0; i < arrStmt.size(); i++)
				((Statement)arrStmt.get(i)).close();
			arrStmt.clear();
		}
	}

	public final void close() throws Exception
	{
		if(conn != null && !isClosed())
		{
			closeStatements();
			ConnectionManager.getInstance().freeConnection(this);
		}
	}

	public final boolean isClosed() throws SQLException
	{
		return conn.isClosed();
	}

	protected Statement createStatement() throws SQLException{
		if(isClosed()) return null;
		Statement stmt = conn.createStatement();
		arrStmt.add(stmt);
		return stmt;
	}

	protected Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException{
		if(isClosed()) return null;
		Statement stmt = conn.createStatement(resultSetType, resultSetConcurrency);
		arrStmt.add(stmt);
		return stmt;
	}

	protected PreparedStatement createPreparedStatement(String sql) throws SQLException{
		PreparedStatement stmt = conn.prepareStatement(sql);
		arrStmt.add(stmt);
		return stmt;
	}

	public void finalize(){
		try{
			this.close();
		}catch(Exception e){
			
		}
	}
}